import time
import requests
import datetime
import pandas as pd

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"
}


def weather40d(areaid):
    '''
    根据areaid爬取40天预报
    :param areaid:
    :return: 返回list类型  或者None
    '''
    t_stamp = int(time.time() * 1000)
    month = str(datetime.datetime.now().year) + str(datetime.datetime.now().month).zfill(2)

    url = 'http://d1.weather.com.cn/calendar_new/2021/{0}_{1}.html?_={2}'.format(areaid, month, t_stamp)
    print(url)

    response = requests.get(url, headers=headers)  # 生成一个response对象
    print("状态码:" + str(response.status_code))  # 打印状态码
    if response.status_code != 200:
        return None

    res = list()  # 保存结果
    s = response.text[response.text.find('['):]
    obj = eval(s)

    for ele in obj:
        res.append({'date': ele['date'], 'max_temp': ele['hmax'], 'min_temp': ele['hmin'], 'rain_poss': ele['hgl']})
    return res

# print(pd.DataFrame.from_dict(weather40d(101340404)))
